//
//  HJEmoticonKeyboardView.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/10/8.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit
let emoticonKeyboardHeight: CGFloat = 220
let emoticonToolBarHeight: CGFloat = 37

private let EmoticonCellId = "EmoticonCellId"

class HJEmoticonKeyboardView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
                setupUI()
        
        //测试
       // print(HJEmoticonTools.sharedEmoticonTools.allEmoticons)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private func setupUI() {
        
        addSubview(toolbar)
        addSubview(collectionView)
        addSubview(pageControl)
        addSubview(recentLable)
        
        toolbar.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self)
            make.height.equalTo(emoticonToolBarHeight)
        }
        
        pageControl.snp.makeConstraints { (make) in
            
            make.left.right.equalTo(self)
            make.bottom.equalTo(self.toolbar.snp.top)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.right.left.top.equalTo(self)
            make.bottom.equalTo(self.toolbar.snp.top)
        }
        
        recentLable.snp.makeConstraints { (make) in
            make.center.equalTo(pageControl)
        }
    
        //实现toolbar闭包
        toolbar.emoticonTypeSelectClosure = { type in
            let indexPath = IndexPath(item: 0, section: type.rawValue)
            self.collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: true)
            self.updatePageControlData(indexPath: indexPath)
        }
        
        
        //设置UI界面的时候 就手动调用更新数据的方法
        //主队列异步 实际上还是主队列 当前任务的优先级是比较低优先级 等到主队列空闲的时候 才会执行代码块中的任务
        DispatchQueue.main.async {
            self.updatePageControlData(indexPath: IndexPath(item: 0, section: 0))
        }
        
        regsiterNotification()
    }
    //接收归档时发送的通知
    func regsiterNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: Notification.Name(KsaveRecentEmoticon), object: nil)
    }
    
    func reloadData() {
        
        let indexPath = collectionView.indexPathsForVisibleItems.last!
        
        if indexPath.section != 0 {
            collectionView.reloadItems(at: [IndexPath(item: 0, section: 0)])
        }
    }
    
    
    //添加底部工具条
    lazy var toolbar : HJEmoticonToolBar = HJEmoticonToolBar()
    
    //最近提示文字
    lazy var recentLable : UILabel = UILabel(title: "最近使用表情", textColor: UIColor.orange, fontSize: 10)
    
    //添加pageControl
    lazy var pageControl : UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.currentPage = 2
        pageControl.numberOfPages = 5
        
        //使用KVC为私有属性赋值
        //可以在OC运行时LLDB上看
        pageControl.setValue(#imageLiteral(resourceName: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageControl.setValue(#imageLiteral(resourceName: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        return pageControl
        
    }()
    
    //添加CollectionView
    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.itemSize = CGSize(width: KScreenW, height: emoticonKeyboardHeight - emoticonToolBarHeight)
        let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        //注册cell
        cv.register(HJEmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellId)
        cv.delegate = self
        cv.dataSource = self
        cv.isPagingEnabled = true
        cv.bounces = false
        
        return cv
    }()
    
    //根据indexPath 更新pageControl
    func updatePageControlData(indexPath: IndexPath) {
        let pageEmoticons = HJEmoticonTools.sharedEmoticonTools.allEmoticons[indexPath.section]
        
        pageControl.numberOfPages = pageEmoticons.count
        pageControl.currentPage = indexPath.item
        
        //设置最近文本和pageControl的显示
        pageControl.isHidden = indexPath.section == 0
        recentLable.isHidden = indexPath.section != 0
    }
}


extension HJEmoticonKeyboardView : UICollectionViewDelegate,UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        let sectionEmotion = HJEmoticonTools.sharedEmoticonTools.allEmoticons
        return sectionEmotion.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let sectionEmotion = HJEmoticonTools.sharedEmoticonTools.allEmoticons
        return sectionEmotion[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCellId, for: indexPath) as! HJEmoticonCell
        
        let emoticons = HJEmoticonTools.sharedEmoticonTools.allEmoticons[indexPath.section][indexPath.item]
        cell.emoticons = emoticons
        return cell
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offsetX = scrollView.contentOffset.x + 0.5 * KScreenW
        let point = CGPoint(x: offsetX, y: 1)
        
        //根据一个点来确定indexPath
        let indexPath = collectionView.indexPathForItem(at: point)
        
        //调用toolbar的方法
        self.toolbar.setEmoticonTypeSelected(indexpath: indexPath!)
        
        //更新pageControl
        self.updatePageControlData(indexPath: indexPath!)
    }
    
}





